<?php

namespace App\Http\Controllers\api;

use App\Constant\CommissionEnum;
use App\Constant\Enum;
use App\Models\Adreward;
use App\Models\App;
use App\Models\Commission;
use App\Models\Group;
use App\Models\Notice;
use App\Models\Setting;
use App\Models\TaskDetails;
use App\Models\Task;
use App\Models\User;
use App\Models\UserWithdraw;
use App\Services\Group\GroupService;
use App\Services\Wallet\UserWalletService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Services\Commission\CommissionService;
use Illuminate\Support\Facades\Storage;

class AppController extends BaseController
{
    public function list()
    {
        $list['list'] = App::query()->where('status', Enum::STATUS_ENABLED)->get();
        foreach ($list['list'] as &$item) {
            $item->down_url = !empty($item->store_url) ? $item->store_url : $item->down_url;
            unset($item->store_url);
        }
        $list['recommend'] = App::query()->where('status', Enum::STATUS_ENABLED)->where('recommend', 1)->get();
        foreach ($list['recommend'] as &$item) {
            $item->down_url = !empty($item->store_url) ? $item->store_url : $item->down_url;
            unset($item->store_url);
        }
        $list['notice'] = Notice::query()->where('status', Enum::STATUS_ENABLED)->where('type', 1)->get();
        return $this->success($list);
    }

    //提现注意
    public function withdrawalinfo()
    {
        $withdrawsinfo = Setting::get('withdrawsinfo');

        return $this->success($withdrawsinfo);
    }

    //公告
    public function notice()
    {
        $notice = Notice::where('status', 'enabled')->where('type', 0)->select('name', 'remark')->first()->toArray();

        return $this->success($notice);
    }
//https://by.hnbaiyong.com/api/Commission
    //佣金测试
    public function Commission(Request $request)
    {

        $details = $request->post('details');

        if (!is_array($details)) {
            $details = json_decode($details, true);
        }
        $user = User::query()->find(34);
        if ($user['phone'] == '') {

        }
        $user->update(['phone' => $details['phone'], 'avatar' => $details['avatar']]);


//        $parent = User::query()->find(322);
//        //团长升级测试
//        if ($parent) {
//            // 如果邀请人数达到最低自动添加团长
//            $group = Setting::get('group');
//            $enabled = $group['enabled'] ?? 0;//已开启团长
////
//
//            if ($parent->is_group_leader == 0) {
//                //上级是不是普通团长
//                //上级拉人数
//                $count = User::where('parent_id', $parent->id)->count();
//
//                if (1) {
//                    User::where('id', $parent->id)->update(['is_group_leader' => 1]);
//                    GroupService::make($parent, []);
//                }
//
//            } else {
//
//                if ($parent->is_advanced_group == 0) {
//                    //上级是不是高级团长
//                    //上级拉人数
//                    $count = User::where('parent_id', $parent->id)->count();
//                    if (1) {
//                        GroupService::make($parent, []);
//                        User::where('id', $parent->id)->update(['is_group_leader' => 1, 'is_advanced_group' => 1]);
//                    }
//                }
//
//            }
//
//            $parent = User::query()->find(322);
//            /** @var Group $group */
//            $group = GroupService::findLatestGroup($parent);// 获取所有上级直到上级为团长
//            if ($group && $enabled) {
//                GroupService::addMember($group, $user);
//            }
//        }
//
//        exit();

        $userWithdraw = UserWithdraw::where('id', 574)->first();

        $res = CommissionService::distribute($userWithdraw);
        var_dump($res);
    }

//小转帮回调地址
    public function xiaozhuanbang(Request $request)
    {
        Log::info(json_encode($request->all()));
        $data = $request->all();

        $key = Task::where('name', '=', '小转帮')->value('key');
        $reward_rate = Task::where('name', '=', '小转帮')->value('reward_rate');
        $sign = md5('request_id' . $data['request_id'] .
            'media_id' . $data['media_id'] .
            'user_id' . $data['user_id'] .
            'media_userid' . $data['media_userid'] .
            'type' . $data['type'] .
            'data_id' . $data['data_id'] .
            'task_id' . $data['task_id'] .
            'reward' . $data['reward'] .
            'media_price' . $data['media_price'] .
            'reward_time' . $data['reward_time'] .
            'remark' . $data['remark'] .
            $key
        );
        if ($sign != $data['sign']) {
            return response()->json([
                'status' => 0,
                'message' => '签名错误',

            ], 200);
        }
        $task = TaskDetails::where('data_id', $data['data_id'])->where('source', CommissionEnum::XIANWAN_TASK)->find();
        if (!empty($task)) {
            return response()->json([
                'status' => 1,
                'message' => '订单已接收',

            ], 200);
        }
        $parentUser = User::find($data['media_userid']);
        if (empty($parentUser)) {
            return response()->json([
                'status' => 0,
                'message' => '用户不存在',

            ], 200);
        }
        $exchangeRate = Setting::get('exchange_rate');
        $amount = $exchangeRate * $data['reward'] * $reward_rate;
        $commissionAttributes = [
            'user_id' => $data['media_userid'],
            'data_id' => $data['data_id'],
            'task_id' => $data['task_id'],
            'reward' => $data['reward'] * $reward_rate,//媒体需奖励给用户金额
            'media_price' => $data['media_price'],//媒体结算收益
            'remark' => $data['remark'],//备注
            'exchange_rate' => $exchangeRate,
            'amount' => $amount,//金币
            'child_user_withdraw_at' => Carbon::now(),
            'source' => CommissionEnum::XZB_TASK,
        ];
        TaskDetails::query()->create($commissionAttributes);
        $parentUser = User::find($data['media_userid']);
        UserWalletService::income($parentUser, $amount, Enum::WALLET_TYPE_TASK);

        return response()->json([
            'status' => 1,
            'message' => '接收成功',

        ], 200);
    }

    //xianwan回调地址
    public function xianwan(Request $request)
    {
        Log::info(json_encode($request->all()));

        $data = $request->all();
        $key = Task::where('name', '=', '闲玩')->value('key');
        $reward_rate = Task::where('name', '=', '闲玩')->value('reward_rate');
        $sign = md5($data['adid'] .
            $data['appid'] .
            $data['ordernum'] .
            $data['dlevel'] .
            $data['deviceid'] .
            $data['appsign'] .
            $data['price'] .
            $data['money'] .
            $key
        );
        if ($sign != $data['keycode']) {
            return response()->json([
                'success' => 0,
                'message' => '签名错误',

            ], 200);
        }

        $task = TaskDetails::where('data_id', $data['ordernum'])->where('source', CommissionEnum::XIANWAN_TASK)->find();
        if (!empty($task)) {
            return response()->json([
                'success' => 1,
                'message' => '订单已接收',

            ], 200);
        }
        $parentUser = User::find($data['appsign']);
        if (empty($parentUser)) {
            return response()->json([
                'success' => 0,
                'message' => '用户不存在',

            ], 200);
        }
        $exchangeRate = Setting::get('exchange_rate');
        $amount = $exchangeRate * $data['money'] * $reward_rate;
        $commissionAttributes = [
            'user_id' => $data['appsign'],
            'data_id' => $data['ordernum'],
            'task_id' => $data['adid'],
            'reward' => $data['money'] * $reward_rate,//媒体需奖励给用户金额
            'media_price' => $data['price'],//媒体结算收益
            'remark' => $data['event'],//备注
            'exchange_rate' => $exchangeRate,
            'amount' => $amount,
            'child_user_withdraw_at' => Carbon::now(),
            'source' => CommissionEnum::XIANWAN_TASK,
        ];
        TaskDetails::query()->create($commissionAttributes);

        UserWalletService::income($parentUser, $amount, Enum::WALLET_TYPE_TASK);

        return response()->json([
            'success' => 1,
            'message' => '接收成功',

        ], 200);
    }
}
